<template>
    <div class="form-page">
        <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
      >
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="用户名"/>
        </el-form-item>
        <el-form-item prop="password">
            <PasswordInput v-model="form.password" placeholder="密码"/>
        </el-form-item>
        <el-form-item prop="confirmPassword">
            <PasswordInput v-model="form.confirmPassword" placeholder="确认密码"/>
        </el-form-item>
        <el-form-item>
          <AsyncButton class="submit-btn" :loading="loading" type="primary" @click="submitForm(formRef)">
            注册
          </AsyncButton>
        </el-form-item>
        <el-row justify="space-between">
            <el-col :sm="7" :xs="8">
                <router-link to="login"><el-button link>登录</el-button></router-link>
            </el-col>
            <el-col :sm="7" :xs="8">
                <router-link to="register"><el-button link>忘记密码</el-button></router-link>
            </el-col>
        </el-row>
      </el-form>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { registerAdmin } from '@/api/index'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import PasswordInput from '@/components/passwordInput/index.vue'

const router = useRouter()

const form = ref({
    username: '',
    password: '',
    confirmPassword: '',
});

const rules = {
    username: [
        { required: true, message: '请输入用户名' },
    ],
    password: [
        { required: true, message: '请输入密码' },
    ],
    confirmPassword: [
        { required: true, message: '请输入确认密码' },
        { validator: validatePassword },
    ],
}

function validatePassword(rule, value, callback){
    console.log(form.value.password, value, 'confirmPassword')
    if(value === '') {
        callback(new Error('请输入确认密码'))
    }else if(value !== form.value.password){
        callback(new Error('确认密码不一致'))
    }else {
        callback()
    }
}

const formRef = ref(null);

const loading = ref(false)

function submitForm(formRef){
    formRef.validate(valid => {
        if(valid){
            loading.value = true
            registerAdmin(form.value).then(res => {
                loading.value = false
                if(res.code === 200){
                    router.push('/login?identifier=' + form.value.username)
                }else{
                    ElMessage.error(res.msg)
                }
            }).catch(err => {
                console.log(err ,'err')
                loading.value = false
            })
        }
    });
}
</script>

<style lang="scss">
@import '@/assets/css/form-page.scss';
</style>